<?php

namespace App\Tools;
use App\Tools\Wechat;

class SignTemplate {
    private $templateId = "1rUt-UMSiqFs34bUpp2SeMVR8AQq1N-gbHeHoSOat8E";
    public $toUser = null;
    public $student = null;
    public $course = null;
    public $status = null;
    public $remain = null;
    public $url = null;
    
    public function __construct($toUser = null, $student = null, $course = null, $status = null, $remain = null, $url = null) {
        $this->toUser = $toUser;
        $this->student = $student;
        $this->course = $course;
        $this->status = $status;
        $this->remain = $remain;
        $this->url = $url;
    }
    private function getData(){
        return [
            'touser' => $this->toUser,
            'template_id' => $this->templateId,
            'url' => $this->url, // 点击消息后跳转的链接，可选,
            'data' => [
                'thing8' => ['value' => $this->student], // 学员姓名,
                'thing2' => ['value' => $this->course],
                'short_thing7' => ['value' => $this->status], // 签到状态,
                'character_string27' => ['value' => $this->remain], // 剩余次数,
            ]
        ];
    }
    public function send() {
        // 检查数据是否完整
        if (!($this->toUser && $this->student && $this->course && $this->status && $this->remain)) {
            throw new \Exception("模版消息缺少必要的参数:" );
        }

        $wechat = Wechat::getInstance();
        $token = $wechat->getAccessToken()->getToken();
        $client = $wechat->getClient();
       
        $templateData = $this->getData();
        // dd($templateData);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
        $result = $client->postJson($url, $templateData);
        if ($result['errcode'] != 0) {
            throw new \Exception("模版消息发送失败: " . $result['errmsg']);
        }
    }
}